package com.whf.android.jar.tool;

import com.blankj.utilcode.util.NetworkUtils;
import com.whf.android.jar.net.HttpCode;

import org.jetbrains.annotations.NotNull;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * exception handling
 *
 * @author : qf.
 * @author wang.hai.fang
 * @since 2.5.0
 */
public abstract class Observer<T> implements io.reactivex.Observer<T> {

    /**
     * 错误提示
     *
     * @param code:int
     * @param error:String
     */
    public abstract void onError(int code, String error);

//    public abstract void onNextObj(Object object);

    @Override
    public void onError(@NotNull Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            onError(code, e.getMessage());
        } else if (e instanceof ConnectException) {
            onError(HttpCode.CODE_404, NetworkUtils.isConnected() ? "连接不到服务器，请稍后重试" : "连接不到服务器，请检查网路");
        } else if (e instanceof SocketException) {
            onError(HttpCode.CODE_404, "连接服务器错误，请稍后重试");
        } else if (e instanceof SocketTimeoutException) {
            onError(HttpCode.CODE_404, "连接服务器超时，请稍后重试");
        } else {
            onError(HttpCode.CODE_605, "未知错误:" + e.getMessage());
        }
    }


    @Override
    public void onSubscribe(@NotNull Disposable d) {
    }

    @Override
    public void onComplete() {

    }

}
